package com.swlz.servlet.admin;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;
import com.swlz.R;
import com.swlz.dto.MallSearch;
import com.swlz.dto.UserFormDTO;
import com.swlz.dto.UserSearch;
import com.swlz.entity.MallProduct;
import com.swlz.entity.User;
import com.swlz.service.MallProductService;
import com.swlz.service.MallTypeService;
import com.swlz.service.impl.MallProductServiceImpl;
import com.swlz.service.impl.MallTypeServiceImpl;
import com.swlz.servlet.HttpServletSupport;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;

import com.swlz.service.WebFileService;
import com.swlz.service.impl.WebFileServiceForGoFastDFS;

@WebServlet("/admin/product.let")
public class ProductServlet extends HttpServletSupport{
	private MallTypeService malltypeService =new MallTypeServiceImpl();
	private MallProductService mallProductService=new MallProductServiceImpl();

//	action="admin/product.let?action=updateProduct" method="POST">
	public Object malltpye() throws Exception {
		return malltypeService.list();
	}
	
	public Object page(MallSearch search) throws Exception {	
		
		return mallProductService.pages(search);
	}
	
	public String findProduct(MallProduct product,HttpServletRequest request) throws Exception {
		request.setAttribute("product", mallProductService.get(product.getProductId()));
		request.setAttribute("productType", malltypeService.get(mallProductService.get(product.getProductId()).getMallTypeId()));
		log.debug(product.toString());
		return "forward:/admin/product/findProduct.jsp";
	}
	
	public Object delete(MallProduct product) throws Exception {
		log.debug(product.toString());
		mallProductService.delete(product.getProductId());
		return R.ok();
	}
	
	public String updateProductForm(MallProduct product,HttpServletRequest request) throws Exception {
		log.debug(product.toString());
		request.setAttribute("product", mallProductService.get(product.getProductId()));
		request.setAttribute("productType", malltypeService.get(mallProductService.get(product.getProductId()).getMallTypeId()));
		
		return "forward:/admin/product/updateProduct.jsp";
	}
	
	public String updateProduct(MallProduct product,HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug(product.toString());
//		product.setProductImgs("front/images/"+product.getProductImgs());
		log.debug(product.toString());
		mallProductService.update(product);
		return "forward:/admin/product/productPage.jsp";
	}
	
	
	
	public String addUser(MallProduct product,HttpServletRequest request) throws Exception {
		log.debug(product.toString());
		
		mallProductService.add(product);
		return "forward:/admin/product/productPage.jsp";
	}
	
	//创建一个下载的方法，需要时调用
		 public static void upload(HttpServletRequest request, HttpServletResponse response,MallProduct user) {
				 	//1.创建一个磁盘工厂对象
				DiskFileItemFactory factory = new DiskFileItemFactory();
				
				//2.通过工厂对象创建上传对象
				ServletFileUpload fUpload = new ServletFileUpload(factory);
				
				//3.通过上传对象解析前端发送的复合型表单数据
				List<FileItem> list = null;
				HashMap<String, String> map = new HashMap<>();
				try {
					//设置字符编码
					request.setCharacterEncoding("utf-8");
				    //通过上传对象解析请求中的数据,获得集合
				    list = fUpload.parseRequest(request);
				    for (FileItem fItem:list) {
				        //判断是否非文本信息
				        if(!fItem.isFormField()){
				            //2.修改上传图片的名字
				            //使用UUID--生成唯一的ID值---wehfiw123%@#$!6fwef_f.jpg
				            UUID uuid = UUID.randomUUID();
				            String path = request.getServletContext().getRealPath("Upload");
				            File file = new File(path);
				            if(!file.exists()){
				                file.mkdirs();
				            }
				            //拼接路径和图片名字(uuid生成的随机字符串拼接上图片名字)
				            File file1 = new File(file, uuid.toString() + "_" + fItem.getName());
				            System.out.println(file1);
				            IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));
				            //存储的路径不能为绝对路径
				            user.setProductImgs("front/images/"+uuid.toString() + "_" + fItem.getName());
				            
				            System.out.println("front/images/"+uuid.toString() + "_" + fItem.getName());
				        }else{
				            //通过key(getFieldNmae--表单的name属性值)获取value(getString--表单的value值)
				            String value = map.get(fItem.getFieldName());
				            //第一次存储
				            if(value == null){
				                map.put(fItem.getFieldName(),new String(fItem.getString().getBytes("ISO-8859-1"),"utf-8"));
				            }else{//多次存储(多选框)
				                map.put(fItem.getFieldName(),value+","+fItem.getString());
				            }
				        }
				    }
				    
					
				} catch (FileUploadException e) {
				    e.printStackTrace();
				} catch (FileNotFoundException e) {
				    e.printStackTrace();
				} catch (IOException e) {
				    e.printStackTrace();
				} 

		 }
}

